import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);
/* Layout */
import Layout from "@/layout";
// 导入vuex仓库对象
import store from "@/store";
import { asyncRoutes } from "@/router/dynamicRoute";
export const routes = [
  {
    path: "/login",
    component: () => import("@/views/Login/index"),
    // hidden: true
  },
  {
    path: "/",
    component: Layout,
    redirect: "/workbench",
  },
  // 添加月卡
  {
    path: "/cardAdd",
    component: () => import("@/views/Car/CarCard/cardAdd"),
    hidden: true,
  },
  // 添加角色
  {
    name: "roleAdd",
    path: "/roleAdd",
    component: () => import("@/views/System/Role/addRole"),
  },
  //编辑角色
  {
    path: "/roleEdit",
    component: () => import("@/views/System/Role/editRole"),
  },
  // 添加企业
  {
    path: "/exterpriseAdd",
    component: () => import("@/views/Park/Enterprise/addItem"),
  },
  // 查看合同
  {
    path: "/exterpriseDetail",
    component: () => import("@/views/Park/Enterprise/Detail"),
  },

  {
    path: "/workbench",
    component: Layout,
    children: [
      {
        path: "",
        component: () => import("@/views/Workbench/index"),
        meta: { title: "工作台", icon: "el-icon-data-board" },
      },
    ],
  },
];
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map((item) => {
    return item.split(":")[0];
  });
  return [...new Set(newArr)];
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map((item) => {
    const arr = item.split(":");
    return `${arr[0]}:${arr[1]}`;
  });
  return [...new Set(newArr)];
}
// 根据权限标识过滤路由表
/** *
 * @param {*} firstRoutePerms ['park','parking',...]
 * @param {*} secondRoutePerms  ['park:building','parking:area',...]
 * @param {*} dinamicRoutes 动态路由规则表
 * @returns
 */
function getRoutes(firstRoutePerms, secondRoutePerms, dinamicRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return dinamicRoutes
    .filter((route) => {
      return firstRoutePerms.includes(route.permission);
    })
    .map((item) => {
      // 2. 对二级路由做过滤
      return {
        ...item,
        children: item.children.filter((item) =>
          secondRoutePerms.includes(item.permission)
        ),
      };
    });
}
const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    mode: "history",
    scrollBehavior: () => ({ y: 0 }),
    routes: routes,
  });

const router = createRouter();
//3 -----------------------------------------------------------------------------------路由守卫
router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token;
  if (to.path === "/big-screen") {
    resetRouter()
    next();
  }
  if (to.path === "/login") {
    if (token) {
      // 如果已经登录，重定向到工作台
      next("/workbench");
    } else {
      // 如果未登录，放行
      next();
    }
  } else {
    if (token) {
      // 如果已经登录，放行
      next();
      // 获取权限列表
      if (!store.state.user.profile.id) {
        const permissions = await store.dispatch("user/getProfile");
        console.log("权限列表", permissions);
        // 处理一级和二级菜单标识
        const firstRoutePerms = getFirstRoutePerms(permissions);
        console.log(firstRoutePerms);
        const secondRoutePerms = getSecondRoutePerms(permissions);
        console.log(secondRoutePerms);
        // 根据权限标识过滤路由表
        const filterRoutes = getRoutes(
          firstRoutePerms,
          secondRoutePerms,
          asyncRoutes
        );
        //addRoute动态添加路由
        // '*:*:*' 表示管理员，拥有所有的权限
        if (permissions.includes("*:*:*")) {
          // 添加路由并且调用setMenuList
          asyncRoutes.forEach((item) => router.addRoute(item));
          store.commit("menu/setMenuList", asyncRoutes);
        } else {
          // 添加路由
          filterRoutes.forEach((item) => router.addRoute(item));
          store.commit("menu/setMenuList", filterRoutes);
        }
        router.addRoute({
          path: "*",
          name:'NotFound',
          component: () => import("@/views/404"),
          hidden: true,
        });
      }
    } else {
      // 如果未登录，重定向到登录页
      next("/login");
    }
  }
});
// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter();
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher;
}

export default router;
